<template>
    <div class="cloud-disk">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
            <div class="left-tools">
                <el-button-group>
                    <el-upload
                        class="upload-btn"
                        :auto-upload="true"
                        :show-file-list="false"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :on-progress="handleUploadProgress"
                        :before-upload="handleBeforeUpload"
                        :http-request="customUpload"
                        :multiple="false"
                        name="file"
                    >
                        <el-button type="primary">
                            <el-icon><Upload /></el-icon>上传文件
                        </el-button>
                    </el-upload>
                    <el-button @click="showNewFolderDialog">
                        <el-icon><FolderAdd /></el-icon>新建文件夹
                    </el-button>
                </el-button-group>
                
                <el-button-group v-if="multipleSelection.length > 0">
                    <el-button 
                        type="primary"
                        @click="handleBatchDownload"
                    >
                        <el-icon><Download /></el-icon>批量下载
                    </el-button>
                    <el-button 
                        type="danger"
                        @click="handleBatchDelete"
                    >
                        <el-icon><Delete /></el-icon>批量删除
                    </el-button>
                </el-button-group>
            </div>
            <div class="right-tools">
                <el-input
                    v-model="searchQuery"
                    placeholder="搜索文件（支持名称、类型、大小）"
                    class="search-input"
                    clearable
                >
                    <template #prefix>
                        <el-icon><Search /></el-icon>
                    </template>
                    <template #append>
                        <el-popover
                            placement="bottom"
                            :width="300"
                            trigger="hover"
                        >
                            <template #reference>
                                <el-icon><QuestionFilled /></el-icon>
                            </template>
                            <div class="search-help">
                                <h4>搜索提示：</h4>
                                <p>- 直接输入关键字搜索文件名</p>
                                <p>- 输入 ">1MB"、"<500KB" 等条件搜索文件大小</p>
                            </div>
                        </el-popover>
                    </template>
                </el-input>
            </div>
        </div>

        <!-- 导航路径 -->
        <div class="path-nav">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item 
                    class="breadcrumb-item" 
                    @click="navigateTo(-1)"
                >
                    全部文件
                </el-breadcrumb-item>
                <el-breadcrumb-item 
                    v-for="(path, index) in currentPath" 
                    :key="index"
                    class="breadcrumb-item"
                    @click="navigateTo(index)"
                >
                    {{ path }}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <!-- 文件列表 -->
        <div class="file-list">
            <el-table
                :data="filteredFiles"
                style="width: 100%;background: rgba(255, 255, 255, 0);"
                @row-click="handleRowClick"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    type="selection"
                    width="55"
                />
                <el-table-column prop="name" label="文件名" min-width="200">
                    <template #default="scope">
                        <div class="file-name" :class="{ 'is-folder': scope.row.type === 'folder' }">
                            <el-icon :size="20" class="file-icon">
                                <component :is="getFileIcon(scope.row)"/>
                            </el-icon>
                            {{ scope.row.name }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="size" label="大小" width="120">
                    <template #default="scope">
                        {{ formatFileSize(scope.row.size) }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="修改时间" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.updateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="scope">
                        <el-button-group>
                            <el-button 
                                size="small"
                                @click="handlePreview(scope.row)"
                                :disabled="scope.row.type === 'folder'"
                            >
                                <el-icon><View /></el-icon>预览
                            </el-button>
                            <el-button 
                                size="small"
                                type="primary"
                                @click="handleDownload(scope.row)"
                                :disabled="scope.row.type === 'folder'"
                            >
                                <el-icon><Download /></el-icon>下载
                            </el-button>
                            <el-button 
                                size="small"
                                type="success"
                                @click="handleShare(scope.row)"
                            >
                                <el-icon><Share /></el-icon>分享
                            </el-button>
                            <el-button 
                                size="small"
                                type="danger"
                                @click="handleDelete(scope.row)"
                            >
                                <el-icon><Delete /></el-icon>删除
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新建文件夹对话框 -->
        <el-dialog
            v-model="newFolderDialogVisible"
            title="新建文件夹"
            width="30%"
        >
            <el-input v-model="newFolderName" placeholder="请输入文件夹名称"/>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="newFolderDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="createNewFolder">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 预览对话框 -->
        <el-dialog
            v-model="previewVisible"
            :title="previewTitle"
            width="90%"
            destroy-on-close
            :close-on-click-modal="false"
        >
            <div class="preview-container">
                <div v-if="isLoading" class="loading-placeholder">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <span>加载中...</span>
                </div>
                
                <!-- 图片预览 -->
                <el-image
                    v-else-if="previewMode === 'image'"
                    :src="previewUrl"
                    fit="contain"
                    class="preview-image"
                    @error="handlePreviewError"
                />
                
                <!-- PDF预览 -->
                <iframe
                    v-else-if="previewMode === 'pdf'"
                    :src="previewUrl"
                    class="preview-iframe"
                    type="application/pdf"
                    width="100%"
                    height="100%"
                />

                <!-- Office文档预览 -->
                <iframe
                    v-else-if="previewMode === 'office'"
                    :src="previewUrl"
                    class="preview-iframe"
                    frameborder="0"
                    allowfullscreen="true"
                    webkitallowfullscreen="true"
                />
                
                <!-- 文本编辑器 -->
                <div v-else-if="previewMode === 'editor'" class="editor-container">
                    <div class="editor-toolbar">
                        <el-button-group>
                            <el-button @click="toggleEdit">
                                {{ isEditing ? '预览' : '编辑' }}
                            </el-button>
                            <el-button 
                                v-if="isEditing"
                                type="primary"
                                @click="saveEditContent"
                            >
                                保存
                            </el-button>
                        </el-button-group>
                    </div>
                    
                    <div v-if="isEditing" class="editor-wrapper">
                        <el-input
                            v-model="editContent"
                            type="textarea"
                            :rows="20"
                            resize="none"
                            class="text-editor"
                        />
                    </div>
                    <pre v-else class="preview-text">{{ editContent }}</pre>
                </div>
                
                <!-- 错误提示 -->
                <div v-else class="error-placeholder">
                    <el-icon class="error-icon"><Warning /></el-icon>
                    <span>预览加载失败</span>
                    <el-button size="small" @click="handleDownload(previewFile)">
                        下载查看
                    </el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 上传进度对话框 -->
        <el-dialog
            v-model="isUploading"
            title="文件上传中"
            width="30%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="false"
        >
            <div class="upload-progress">
                <p>正在上传: {{ uploadFileName }}</p>
                <el-progress 
                    :percentage="uploadProgress" 
                    :format="(percentage) => percentage + '%'"
                    status="success"
                />
            </div>
        </el-dialog>

        <!-- 分享对话框 -->
        <el-dialog
            v-model="shareDialogVisible"
            title="分享文件"
            width="400px"
        >
            <div class="share-content">
                <div class="share-info">
                    <p>分享文件：{{ shareFileName }}</p>
                    <el-select v-model="shareExpireTime" placeholder="选择有效期">
                        <el-option label="1天" :value="24" />
                        <el-option label="7天" :value="168" />
                        <el-option label="30天" :value="720" />
                        <el-option label="永久" :value="0" />
                    </el-select>
                </div>
                <div v-if="shareUrl" class="share-result">
                    <div class="share-url">
                        <el-input v-model="shareUrl" readonly>
                            <template #append>
                                <el-button @click="copyShareUrl">复制链接</el-button>
                            </template>
                        </el-input>
                    </div>
                    <div class="share-code" v-if="shareCode">
                        <p>提取码：{{ shareCode }}</p>
                        <el-button size="small" @click="copyShareCode">复制提取码</el-button>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="shareDialogVisible = false">关闭</el-button>
                    <el-button type="primary" @click="generateShareLink" v-if="!shareUrl">
                        生成链接
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { 
    Upload, 
    Download,
    FolderAdd,
    Search,
    Delete,
    Folder,
    QuestionFilled,
    View,
    Share,
    Warning,
    Picture,
    Files,  // 文档
    VideoCamera,  // 视频
    Headset,  // 音频
    Platform,  // 可执行文件
    Collection,  // 压缩文件
    Reading,  // 文本文件
    DataLine,  // 数据文件
    More  // 其他类型
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { FileType } from '@/types/note/file';
import type { FileItem, FileListResponse } from '@/types/note/file';
import { 
    uploadFile, 
    downloadFile, 
    getFileList, 
    deleteFile, 
    createFolder,
    previewFileApi,
    batchDownloadFiles,
    batchDeleteFiles,
    generateShareLink
} from '@/api/note/file';
import { ElImage, ElDialog } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
// import { SignUtil } from '@/util/signin';
import request from '@/util/request';
import EditorComponent from '@/components/EditorComponent.vue';

// 状态定义
const searchQuery = ref('');
const currentPath = ref<string[]>([]);
const newFolderDialogVisible = ref(false);
const newFolderName = ref('');
const files = ref<FileItem[]>([]);

// 计算属性
const filteredFiles = computed(() => {
    const query = searchQuery.value.toLowerCase();
    if (!query) return files.value;
    
    return files.value.filter(file => {
        // 匹配文件名
        const nameMatch = file.name.toLowerCase().includes(query);
        
        // 匹配文件类型
        const typeMatch = file.type.toLowerCase().includes(query);
        
        // 匹配文件大小（如：">1MB"、"<500KB" 等）
        let sizeMatch = false;
        if (query.startsWith('>') || query.startsWith('<')) {
            const size = parseFileSize(query.slice(1));
            if (size !== null) {
                sizeMatch = query.startsWith('>') 
                    ? file.size > size 
                    : file.size < size;
            }
        }
        
        return nameMatch || typeMatch || sizeMatch;
    });
});

// 添加文件大小解析函数
const parseFileSize = (sizeStr: string): number | null => {
    const units = {
        'b': 1,
        'kb': 1024,
        'mb': 1024 * 1024,
        'gb': 1024 * 1024 * 1024,
        'tb': 1024 * 1024 * 1024 * 1024
    };
    
    try {
        const matches = sizeStr.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i);
        if (!matches) return null;
        
        const size = parseFloat(matches[1]);
        const unit = (matches[2] || 'b').toLowerCase();
        
        return size * (units[unit as keyof typeof units] || 1);
    } catch {
        return null;
    }
};

// 方法定义
const handleUploadSuccess = async (response: any) => {
    if (!userId.value) return;
    
    try {
        if (response?.url) {
            ElMessage.success('上传成功');
            isUploading.value = false;
            uploadProgress.value = 100;
            await refreshFileList();
        }
    } catch (error) {
        console.error('Upload error:', error);
        ElMessage.error(error instanceof Error ? error.message : '上传失败');
        isUploading.value = false;
    }
};

const handleUploadError = (error: any) => {
    console.error('Upload error:', error);
    ElMessage.error(error.response?.data?.message || '文件上传失败');
    isUploading.value = false;
    uploadProgress.value = 0;
};

const handleUploadProgress = (event: any) => {
    uploadProgress.value = Math.round(event.percent);
};

const showNewFolderDialog = () => {
    newFolderDialogVisible.value = true;
    newFolderName.value = '';
};

const createNewFolder = async () => {
    if (!userId.value || !newFolderName.value) {
        ElMessage.warning('请输入文件夹名称');
        return;
    }

    try {
        const currentFolderPath = currentPath.value.length > 0 
            ? `${currentPath.value.join('/')}/${newFolderName.value}`
            : newFolderName.value;
            
        await createFolder(currentFolderPath, userId.value);
        await refreshFileList();
        newFolderDialogVisible.value = false;
        newFolderName.value = '';
        ElMessage.success('创建成功');
    } catch (error) {
        console.error('Create folder error:', error);
        ElMessage.error('创建文件夹失败');
    }
};

const handleRowDblclick = async (row: FileItem) => {
    if (row.type === FileType.FOLDER) {
        // 更新当前路径
        const newPath = currentPath.value.length > 0 
            ? `${currentPath.value.join('/')}/${row.name}`
            : row.name;
        currentPath.value = newPath.split('/');
        await refreshFileList();
    }
};

const navigateTo = async (index: number) => {
    if (index === -1) {
        // 返回根目录
        currentPath.value = [];
    } else {
        // 导航到指定层
        currentPath.value = currentPath.value.slice(0, index + 1);
    }
    await refreshFileList();
};

const handleDownload = async (file: FileItem) => {
    try {
        await downloadFile(file.id, userId.value, file.name);
        ElMessage.success('下载成功');
    } catch (error) {
        console.error('Download error:', error);
        ElMessage.error('下载失败');
    }
};

const handleDelete = async (file: FileItem) => {
    try {
        await deleteFile(file.id, userId.value);
        ElMessage.success('删除成功');
        await refreshFileList();
    } catch (error) {
        console.error('Delete error:', error);
        ElMessage.error('删除失败');
    }
};

// 工具方法
const formatFileSize = (size: number) => {
    if (size === 0) return '-';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let index = 0;
    while (size >= 1024 && index < units.length - 1) {
        size /= 1024;
        index++;
    }
    return `${size.toFixed(2)} ${units[index]}`;
};

const formatDate = (date: Date) => {
    return new Date(date).toLocaleString();
};

const getFileIcon = (file: FileItem) => {
    if (file.type === 'folder') {
        return Folder;
    }

    const mimeType = file.mimeType?.toLowerCase() || '';
    const extension = file.name.split('.').pop()?.toLowerCase() || '';

    // 图片文件
    if (mimeType.startsWith('image/') || /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(extension)) {
        return Picture;
    }

    // 文档文件
    if (/\.(doc|docx|xls|xlsx|ppt|pptx|pdf)$/i.test(extension) || 
        mimeType.includes('pdf') || 
        mimeType.includes('msword') || 
        mimeType.includes('ms-excel') ||
        mimeType.includes('ms-powerpoint')) {
        return Files;
    }

    // 视频文件
    if (mimeType.startsWith('video/') || /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(extension)) {
        return VideoCamera;
    }

    // 音频文件
    if (mimeType.startsWith('audio/') || /\.(mp3|wav|ogg|m4a|flac)$/i.test(extension)) {
        return Headset;
    }

    // 可执行文件
    if (/\.(exe|msi|bat|cmd|sh)$/i.test(extension)) {
        return Platform;
    }

    // 压缩文件
    if (/\.(zip|rar|7z|tar|gz)$/i.test(extension)) {
        return Collection;
    }

    // 文本文件
    if (/\.(txt|log|ini|json|xml|html|css|js)$/i.test(extension) || 
        mimeType.includes('text/')) {
        return Reading;
    }

    // 数据文件
    if (/\.(dat|db|sql|csv|mdb)$/i.test(extension)) {
        return DataLine;
    }

    // 其他类型
    return More;
};

// 修改刷新文件列表方法
const refreshFileList = async () => {
    if (!userId.value) return;
    
    try {
        const response = await getFileList(
            currentPath.value.length > 0 ? currentPath.value.join('/') : '',
            userId.value
        );
        
        if (Array.isArray(response)) {
            files.value = response.map(file => ({
                id: file.attachmentId.toString(),
                name: file.name,
                path: file.url,
                type: file.fileType === 'folder' ? FileType.FOLDER : getFileType(file),
                size: file.size,
                updateTime: new Date(file.uploadTime),
                mimeType: file.fileType,
                order: file.order
            }));

            // 按 order 排序
            files.value.sort((a, b) => (a.order || 0) - (b.order || 0));
        } else {
            throw new Error('Invalid response format');
        }
    } catch (error) {
        console.error('Refresh error:', error);
        ElMessage.error('刷新文件列表失败');
    }
};

// 添加预览相关的响应式变量
const previewMode = ref<'image' | 'text' | 'pdf' | 'office' | 'editor' | 'none'>('none');
const previewVisible = ref(false);
const previewUrl = ref('');
const previewTitle = ref('');
const previewFile = ref<FileItem | null>(null);
const previewContent = ref('');
const isLoading = ref(false);

// 判断文件是否可预览
const isPreviewable = (file: FileItem) => {
    const extension = file.name.split('.').pop()?.toLowerCase() || '';
    const contentType = file.mimeType || '';

    // 可预览的Content-Type
    const previewableTypes = {
        // 图片类型
        'image/jpeg': true,
        'image/png': true,
        'image/gif': true,
        'image/bmp': true,
        'image/webp': true,
        'image/tiff': true,
        'image/svg+xml': true,
        
        // 文档类型
        'application/pdf': true,
        'application/msword': true,
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true,
        'application/vnd.ms-excel': true,
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true,
        'application/vnd.ms-powerpoint': true,
        'application/vnd.openxmlformats-officedocument.presentationml.presentation': true,
        
        // 文本类型
        'text/plain': true,
        'text/html': true,
        'text/css': true,
        'text/javascript': true,
        'text/csv': true,
        'text/xml': true,
        'application/json': true,
        'text/markdown': true
    };

    // 可预览的扩展名
    const previewableExtensions = [
        'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg',
        'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
        'txt', 'html', 'css', 'js', 'json', 'xml', 'md', 'log', 'ini'
    ];

    return previewableTypes[contentType] || previewableExtensions.includes(extension);
};

// 修改预览处理方法
const handlePreview = async (file: FileItem) => {
    if (!isPreviewable(file)) {
        ElMessage.warning('该文件类型不支持预览');
        return;
    }

    try {
        isLoading.value = true;
        previewFile.value = file;
        previewTitle.value = file.name;
        previewVisible.value = true;

        const extension = file.name.split('.').pop()?.toLowerCase() || '';

        // 根据文件类型设置预览模式
        if (/^(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(extension)) {
            previewMode.value = 'image';
            previewUrl.value = `/api/minio/preview?attachmentId=${file.id}&userId=${userId.value}`;
        } 
        else if (/^(pdf)$/i.test(extension)) {
            previewMode.value = 'pdf';
            // 使用 PDF.js 预览
            previewUrl.value = `https://mozilla.github.io/pdf.js/web/viewer.html?file=${encodeURIComponent(
                `${window.location.origin}/api/minio/preview?attachmentId=${file.id}&userId=${userId.value}`
            )}`;
        }
        else if (/^(doc|docx|xls|xlsx|ppt|pptx)$/i.test(extension)) {
            previewMode.value = 'office';
            // 使用 Google Docs Viewer 作为备选
            previewUrl.value = `https://docs.google.com/viewer?url=${encodeURIComponent(
                `${window.location.origin}/api/minio/preview?attachmentId=${file.id}&userId=${userId.value}`
            )}&embedded=true`;
        }
        else if (/^(txt|log|ini|json|xml|md|css|js|html)$/i.test(extension)) {
            previewMode.value = 'editor';
            const response = await request.get(`/api/minio/preview`, {
                params: { attachmentId: file.id, userId: userId.value },
                responseType: 'text'
            });
            editContent.value = response.data;
            isEditing.value = false;
        }
        
    } catch (error) {
        console.error('Preview error:', error);
        ElMessage.error('预览加载失败');
    } finally {
        isLoading.value = false;
    }
};

// 添加预览错误处理方法
const handlePreviewError = () => {
    ElMessage.error('预览加载失败');
    previewMode.value = 'none';
    isLoading.value = false;
};

// 添加上传进度状态
const uploadProgress = ref(0);
const isUploading = ref(false);
const uploadFileName = ref('');

// 添加多选状态
const multipleSelection = ref<FileItem[]>([]);
//const isSelectionMode = ref(true);

// 选择变化处理
const handleSelectionChange = (selection: FileItem[]) => {
    multipleSelection.value = selection;
};

// 修改批量下载处理
const handleBatchDownload = async () => {
    const selectedFiles = multipleSelection.value.filter(file => file.type !== 'folder');
    if (selectedFiles.length === 0) {
        ElMessage.warning('请选择要下载的文件');
        return;
    }

    try {
        ElMessage.info(`开始下载 ${selectedFiles.length} 个文件...`);
        await batchDownloadFiles(selectedFiles, userId.value);
        ElMessage.success('下载完成');
    } catch (error) {
        console.error('Batch download error:', error);
        ElMessage.error('批量下载失败');
    }
};

// 修改批量删除处理
const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的文件');
        return;
    }

    ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 个文件/文件夹吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await batchDeleteFiles(multipleSelection.value, userId.value);
            await refreshFileList();
            ElMessage.success('批量删除成功');
        } catch (error) {
            console.error('Batch delete error:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {});
};

// 分享相关状态
const shareDialogVisible = ref(false);
const shareFileName = ref('');
const shareExpireTime = ref(24); // 默认1天
const shareUrl = ref('');
const shareCode = ref('');
const currentShareFile = ref<FileItem | null>(null);

// 处理分享
const handleShare = (file: FileItem) => {
    shareDialogVisible.value = true;
    shareFileName.value = file.name;
    currentShareFile.value = file;
    shareUrl.value = '';
    shareCode.value = '';
};

// 复制分享链接
const copyShareUrl = async () => {
    try {
        await navigator.clipboard.writeText(shareUrl.value);
        ElMessage.success('链接已复制到剪贴板');
    } catch (error) {
        ElMessage.error('复制失败，请手动复制');
    }
};

// 复制提取码
const copyShareCode = async () => {
    try {
        await navigator.clipboard.writeText(shareCode.value);
        ElMessage.success('提取码已复制到剪贴板');
    } catch (error) {
        ElMessage.error('复制失败，请手动复制');
    }
};

// 路径处理
const route = useRoute();
const router = useRouter();

// 获取用户ID
const userId = computed((): number => {
    // const id = SignUtil.getUserId();
    // if (!id) {
    //     ElMessage.error('请先登录');
    //     router.push('/loginRegister');
    //     return 0;
    // }
    // return Number(id);
    return 1;
});

// // 修改上传相关配置
// const uploadHeaders = computed(() => ({
//     'Authorization': SignUtil.getAccessToken(),
//     'Access-Control-Allow-Origin': 'http://qb.sso.com:3000',
//     'Access-Control-Allow-Credentials': 'true'
// }));

// 修改文件上传前的验证
const handleBeforeUpload = (file: File) => {
    // 获取文件扩展名
    const extension = file.name.split('.').pop()?.toLowerCase() || '';
    
    // 允许的文件类型
    const allowedTypes = {
        // 图片类型
        'image/jpeg': true,
        'image/png': true,
        'image/gif': true,
        'image/bmp': true,
        'image/webp': true,
        'image/tiff': true,
        'image/svg+xml': true,
        // 文档类型
        'application/pdf': true,
        'application/msword': true,
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true,
        'application/vnd.ms-excel': true,
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true,
        'application/vnd.ms-powerpoint': true,
        'application/vnd.openxmlformats-officedocument.presentationml.presentation': true,
        // 文本类型
        'text/plain': true,
        'text/html': true,
        'text/css': true,
        'text/javascript': true,
        'text/csv': true,
        'text/xml': true,
        'application/json': true,
        // 压缩文件类型
        'application/zip': true,
        'application/x-rar-compressed': true,
        'application/x-7z-compressed': true,
        'application/x-tar': true,
        'application/gzip': true,
        // 音频类型
        'audio/mpeg': true,
        'audio/wav': true,
        'audio/ogg': true,
        // 视频类型
        'video/mp4': true,
        'video/mpeg': true,
        'video/quicktime': true,
        'video/webm': true
    };

    // 允许的文件扩展名
    const allowedExtensions = [
        // 图片
        'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',
        // 文档
        'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf',
        // 文本
        'txt', 'log', 'ini', 'json', 'xml', 'html', 'css', 'js',
        // 压缩包
        'zip', 'rar', '7z', 'tar', 'gz',
        // 音视频
        'mp4', 'mp3', 'wav'
    ];

    if (!allowedTypes[file.type] && !allowedExtensions.includes(extension)) {
        ElMessage.error('不支持该文件类型!');
        return false;
    }

    // 检查文件大小（50MB）
    const maxSize = 50 * 1024 * 1024;
    if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过 50MB!');
        return false;
    }

    uploadFileName.value = file.name;
    isUploading.value = true;
    uploadProgress.value = 0;
    return true;
};

// 添加文件类型判断函数
const getFileType = (file: FileListResponse): FileType => {
    if (file.fileType === 'folder') return FileType.FOLDER;
    
    const extension = file.name.split('.').pop()?.toLowerCase() || '';

    if (/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(extension)) return FileType.IMAGE;
    if (/\.(doc|docx|xls|xlsx|ppt|pptx|pdf)$/i.test(extension)) return FileType.DOCUMENT;
    if (/\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(extension)) return FileType.VIDEO;
    if (/\.(mp3|wav|ogg|m4a|flac)$/i.test(extension)) return FileType.AUDIO;
    if (/\.(exe|msi|bat|cmd|sh)$/i.test(extension)) return FileType.EXECUTABLE;
    if (/\.(zip|rar|7z|tar|gz)$/i.test(extension)) return FileType.ARCHIVE;
    if (/\.(txt|log|ini|json|xml|html|css|js)$/i.test(extension)) return FileType.TEXT;
    if (/\.(dat|db|sql|csv|mdb)$/i.test(extension)) return FileType.DATA;

    return FileType.OTHER;
};

// 修改自定义上传方法
const customUpload = async (options: any) => {
    try {
        const response = await uploadFile(
            options.file,
            currentPath.value.length > 0 ? currentPath.value.join('/') : '',
            userId.value
        );
        
        if (response?.data) {
            await refreshFileList();
            options.onSuccess(response.data);
        } else {
            throw new Error('上传失败');
        }
    } catch (error) {
        console.error('Upload error:', error);
        options.onError(error);
    } finally {
        isUploading.value = false;
        uploadProgress.value = 0;
    }
};

// 添加单击处理方法
const handleRowClick = (row: FileItem) => {
    if (row.type === FileType.FOLDER) {
        // 更新当前路径
        const newPath = currentPath.value.length > 0 
            ? `${currentPath.value.join('/')}/${row.name}`
            : row.name;
        currentPath.value = newPath.split('/');
        refreshFileList();
    }
};

// 添加预览和编辑相关的响应式变量
const isEditing = ref(false);
const editContent = ref('');

// 修改保存编辑内容方法
const saveEditContent = async () => {
    if (!previewFile.value) return;
    
    try {
        const formData = new FormData();
        const blob = new Blob([editContent.value], { type: 'text/plain' });
        // 使用当前预览文件的名称
        const fileName = previewFile.value.name;
        formData.append('file', blob, fileName);
        formData.append('userId', userId.value.toString());
        formData.append('attachmentId', previewFile.value.id);

        await request.post('/api/minio/update', formData);
        ElMessage.success(`保存 ${fileName} 成功`);
        isEditing.value = false;
        await refreshFileList(); // 刷新文件列表
    } catch (error) {
        console.error('Save error:', error);
        ElMessage.error('保存失败');
    }
};

// 添加编辑切换方法
const toggleEdit = () => {
    isEditing.value = !isEditing.value;
};

onMounted(async () => {
    console.log('Component mounted'); // 添加日志
    // if (!SignUtil.isSignin()) {
    //     ElMessage.error('请先登录');
    //     router.push('/loginRegister');
    //     return;
    // }
    
    try {
        const pathQuery = route.query.path as string;
        if (pathQuery && pathQuery !== '/') {
            currentPath.value = pathQuery.split('/').filter(Boolean);
        }
        console.log('Initial path:', currentPath.value); // 添加日志
        await refreshFileList();
    } catch (error) {
        console.error('Initial load error:', error);
        ElMessage.error('加载文件列表失败');
    }
});
</script>

<style scoped>
.cloud-disk {
    padding: 20px;
    height: calc(100vh - 80px);
    background:  #f5f7fa98;
    margin: 80px auto 0;
    width: var(--width);
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
    margin-top: 5%;
    margin-bottom: 3%;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    /* background: white; */
    padding: 15px;
    /* border-radius: 8px; */
    border-bottom: 1px solid #ec9a9a2d;
}


.left-tools {
    display: flex;
    gap: 10px;
    align-items: center;
}

.left-tools .el-button-group {
    display: inline-flex;
    gap: 8px;
}

.left-tools .el-button {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid #ec9a9a2d;
    color:#409EFF;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
    transition: all 0.3s;
    border:1px solid #409EFF;
}

.left-tools .el-button:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.left-tools .el-button[type="primary"] {
    background: #409EFF;
    border-color: #409EFF;
    color: #fff;
}

.left-tools .el-button[type="primary"]:hover {
    background: #66b1ff;
    border-color: #66b1ff;
}

.left-tools .el-button[type="danger"] {
    background: #f56c6c;
    border-color: #f56c6c;
    color: #fff;
}

.left-tools .el-button[type="danger"]:hover {
    background: #f78989;
    border-color: #f78989;
}

.left-tools .el-icon {
    margin-right: 4px;
    font-size: 16px;
}

.upload-btn {
    display: inline-block;
}

.el-button-group {
    display: inline-flex;
}


.search-input {
    width: 300px;
}

.path-nav {
    padding: 12px 16px;
    background: #f5f7fa00;
    border-radius: 4px;
    margin-bottom: 20px;
}

.file-list {
    background: transparent;
    padding: 20px;
    margin-top: 50px;
    /* border-radius: 8px; */
    border-top: 1px solid #ec9a9a2d;
}

.file-name {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
}

.file-name.is-folder {
    cursor: pointer;
    color: #409EFF;
}

.file-icon {
    color: #409EFF;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
    .toolbar {
        flex-direction: column;
        gap: 15px;
    }
    
    .search-input {
        width: 100%;
    }
}

.share-content {
    padding: 20px 0;
}

.share-info {
    margin-bottom: 20px;
}

.share-result {
    margin-top: 20px;
}

.share-code {
    margin-top: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.share-code p {
    margin: 0;
    font-weight: bold;
}

/* 设置表格背景透明 */
:deep(.el-table) {
    background-color: transparent !important;
}

:deep(.el-table tr) {
    background-color: transparent !important;
}

:deep(.el-table th),
:deep(.el-table td) {
    background-color: transparent !important;
}

/* 去掉表格边框 */
:deep(.el-table--border) {
    border: none;
}

:deep(.el-table::before) {
    display: none;
}

:deep(.el-table__inner-wrapper::before) {
    display: none;
}

/* 新建文件夹对话框样式 */
:deep(.el-dialog) {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid #ec9a9a2d;
}

:deep(.el-dialog__title) {
    font-size: 18px;
    color: #303133;
    font-weight: 500;
}

:deep(.el-dialog__body) {
    padding: 30px 20px;
}

:deep(.el-dialog__footer) {
    padding: 10px 20px 20px;
    border-top: 1px solid #ec9a9a2d;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-dialog__body .el-input) {
    margin-bottom: 10px;
}

:deep(.el-dialog__body .el-input__wrapper) {
    background-color: transparent;
    box-shadow: 0 0 0 1px #dcdfe6;
}

:deep(.el-dialog__body .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409EFF;
}

/* 预览相关样式 */
.preview-container {
    width: 100%;
    height: 80vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f5f7fa;
    position: relative;
    overflow: hidden;
}

.preview-image,
.preview-iframe {
    max-width: 100%;
    max-height: 100%;
    width: 100%;
    height: 100%;
}

.preview-text {
    width: 100%;
    height: 100%;
    overflow: auto;
    padding: 20px;
    margin: 0;
    background: #fff;
    font-family: monospace;
    white-space: pre-wrap;
}

.loading-placeholder,
.error-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    color: #909399;
}

.loading-icon {
    font-size: 32px;
    animation: rotating 2s linear infinite;
}

.error-icon {
    font-size: 32px;
    color: #f56c6c;
}

@keyframes rotating {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.breadcrumb-item {
    cursor: pointer;
}

.breadcrumb-item :deep(.el-breadcrumb__inner) {
    color: #606266;
}

.breadcrumb-item :deep(.el-breadcrumb__inner:hover) {
    color: #409EFF;
}

/* 表格行悬停效果 */
:deep(.el-table__row) {
    cursor: pointer;
}

:deep(.el-table__row:hover) {
    background-color: rgba(64, 158, 255, 0.1) !important;
}

/* 文件夹行样式 */
:deep(.el-table__row.is-folder) {
    &:hover {
        background-color: rgba(64, 158, 255, 0.15) !important;
    }
}

.editor-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.editor-toolbar {
    padding: 10px;
    border-bottom: 1px solid #dcdfe6;
}

.editor {
    flex: 1;
    overflow: auto;
}

.preview-iframe {
    width: 100%;
    height: 100%;
    border: none;
}

.editor-wrapper {
    height: calc(100% - 50px);
    overflow: auto;
    padding: 10px;
}

.text-editor {
    width: 100%;
    height: 100%;
    font-family: monospace;
}

.text-editor :deep(.el-textarea__inner) {
    height: 100%;
    font-family: monospace;
    line-height: 1.5;
    padding: 10px;
}
</style>
